package com.example.volunteeroa.controller;

import com.example.volunteeroa.JpaUtils.DeleteUtils;
import com.example.volunteeroa.entity.Organization;
import com.example.volunteeroa.entity.OrganizationAllocation;
import com.example.volunteeroa.entity.RestBean;
import com.example.volunteeroa.repository.OrganizationAllocationRepository;
import com.example.volunteeroa.repository.OrganizationRepository;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@CrossOrigin
@RestController
@RequestMapping("api/orgalloc")
public class OrganizationAllocationController {
    @Resource
    OrganizationRepository ORepository;
    @Resource
    OrganizationAllocationRepository OARepository;

    @GetMapping()
    public RestBean findAll(){
        List<OrganizationAllocation> all = OARepository.findAll();
        return new RestBean(200,"查询全部成功",all);
    }
    @DeleteMapping()
    public RestBean deleteOrgByID(@RequestBody Organization organization){
        DeleteUtils.deleteOrgAllocByOrgID(ORepository,OARepository,organization);
        return new RestBean(200,"删除组织的分配成功",null);
    }//删除组织的分配但是不删除组织
    @PostMapping("/{orgID}")
    public RestBean add(@PathVariable Integer orgID,@RequestBody List<OrganizationAllocation> organizationAllocations){
        for (int i = 0; i < organizationAllocations.size(); i++) {
            OrganizationAllocation organizationAllocation= organizationAllocations.get(i);
            Optional<Organization> byId = ORepository.findById(orgID);
            //Organization organization = ORepository.findById(byId).get();
            organizationAllocation.setOrg(byId.get());
            OARepository.save(organizationAllocation);
        }
        return new RestBean(200,"添加成功",null);
    }
    @PutMapping()
    public RestBean update(@RequestBody OrganizationAllocation organizationAllocation){
        Optional<OrganizationAllocation> byId = OARepository.findById(organizationAllocation.getOAID());
        OrganizationAllocation organizationAllocation1 = byId.get();
        Integer orgID = organizationAllocation1.getOrg().getOrgID();
        Organization organization = ORepository.findById(orgID).get();
        organizationAllocation.setOrg(organization);
        OARepository.save(organizationAllocation);
        return new RestBean(200,"修改成功",null);
    }
}
